package com.br.jhone.accfc;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.br.jhone.accfc.pojo.Item;
import com.br.jhone.accfc.util.CursorItensAdapter;
import com.br.jhone.accfc.util.DBUtil;
import com.br.jhone.accfc.util.UtilACCFC;

public class ACCFCActivity extends Activity implements OnClickListener, OnItemClickListener {

	private DBUtil mDbUtil;
	private EditText mCpNome;
	private ImageButton mBtPesquisa;
	private ListView mLista;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mDbUtil = new DBUtil(this);
        
        mCpNome = (EditText) findViewById(R.id.cpItem);
        
        mBtPesquisa = (ImageButton) findViewById(R.id.btBuscar);
        mBtPesquisa.setOnClickListener(this);
        
        mLista = (ListView) findViewById(R.id.lista);
        mLista.setOnItemClickListener(this);
    }

	@Override
	public void onClick(View arg0) {
		String nome = mCpNome.getText().toString().trim();
		if(nome.length() > 2 || nome.isEmpty()){
			Cursor c = mDbUtil.listarItens(nome);
			startManagingCursor(c);
			
			CursorItensAdapter antigo = (CursorItensAdapter)mLista.getAdapter();
			if(antigo != null){
				antigo.notifyDataSetInvalidated();
			}
			mLista.setAdapter(new CursorItensAdapter(this, c));
			((CursorItensAdapter)mLista.getAdapter()).notifyDataSetChanged();
		}else{
			Toast.makeText(this, R.string.minimoTresLetras, Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View view, int pos, long id) {
		Item i = mDbUtil.marcarItem((int)id);
		ImageView iv = (ImageView) view.findViewById(R.id.imagemItem);
		iv.setImageResource(UtilACCFC.recuperarDrawableRes(i.getTipo().getId(), i.getPossui()));
		iv.refreshDrawableState();
	}

}